package com.zixun.service.Impl;

import com.zixun.model.Order;
import com.zixun.repository.OrderRepository;
import com.zixun.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.persistence.criteria.*;

/**
 * Created by Basil on 16/8/29.
 */
@Service
public class OrderServiceImpl implements OrderService{

    @Autowired
    private OrderRepository orderRepository;

    @Override
    public Page<Order> findByUserIdPage(final Integer userId, Integer pageIndex, Integer countPerPage) {
        Specification<Order> orderSpecification =new Specification<Order>() {
            @Override
            public Predicate toPredicate(Root<Order> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                Path<Integer> $userId = root.get("userId");
                Predicate _userId = cb.equal($userId,userId);
                return cb.and(_userId);
            }
        };
        Sort sort = new Sort(Sort.Direction.DESC,"createTime");
        Pageable pageable = new PageRequest(pageIndex - 1, countPerPage,sort);
        return orderRepository.findAll(orderSpecification,pageable);
    }
}
